var priceTableObj;
$(function () {
    var now = new Date();
    var year = now.getFullYear();
    var moth= "";
    if (now.getMonth()>=9) {
        moth = now.getMonth()+1
    }else {
        moth="0"+(now.getMonth()+1);
    }
    $("[name=startDate]").val(year+"-"+moth);
    syb("#selectSignOrgName");
    $("#selectSignOrgName option").remove();
    $("#selectSignOrgName").prepend("<option value='0'>全部</option>");
    loadCertificateType('190px','#certificateType', $("#GENERAL_CREDENTIAL").val(), 0);

    $("#certificateSpecialty").select2({
        placeholder: "请选择",
        allowClear: true,
        width: "190px",
        language: "zh-CN"
    });

    //异步加载地区
    Plug.plug_ins(
        "get",
        cmsBaseUrl + "/api/cms/tree_book/v1/get_tree_book_list.do?code=2147483647&type=2&level=1",
        "#certificateArea",
        '请选择地区',
        function () {
        },
        true, '2147483647'
    );

    priceTableObj = $('#myTable').dataTableExtend({
        "ajax": sysInfo.basePath + "/zs/guide_price_config/query_guide_price_list.do",
//			    	"select":true,
        "scrollX": "true",//是否开启横项滚动
        "fixedColumns": {//锁定列，只有开启scrollX时才生效
            "leftColumns": 2,//左侧锁定2列
            "rightColumns": 1//右侧锁定1列
        },
        //搜索条件
        "fnServerParams": function (aoData) {
            aoData.startDate = $('#startDate').val();
            aoData.endDate = $('#endDate').val();
            var signOrgId = $('#selectSignOrgName').val();
            if (signOrgId == 0) {
                signOrgId = "";
            }
            aoData.signOrgId = signOrgId;
            var checkResult = checkHasSybAuth($('#selectSignOrgName option'));
            if (!checkResult) {
                aoData.isAll = "0";
            }
            if ($('#certificateType').val()) {
                aoData.certificateType = $("#certificateType").val();
            }
            if ($('#certificateSpecialty').val()) {
                aoData.certificateSpecialty = $("#certificateSpecialty").val();
            }
            if ($('#certificateLevel').val()) {
                aoData.certificateLevel = $("#certificateLevel").val();
            }
            if ($('#certificateAreaCodes').val()) {
                aoData.certificateArea = $("[name='certificateAreaCodes']").val();
            }
            if ($('#applicationScopes').val()) {
                aoData.applicationScope = $('#applicationScopes').val();
            }
        },
        "aoColumns": [
            {
                "title": "配置id",
                "data": "id",
                "orderable": false,
                "visible": false
            },
            {
                "title": "序号",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    return meta.row + 1;
                }
            },
            {
                "title": "所属事业部",
                "data": "signOrgName",
                "orderable": false
            },
            {
                "title": "所属月份",
                "data": "month",
                "orderable": false
            },
            {
                "title": "证书类型",
                "data": "certificateType",
                "orderable": false
            },
            {
                "title": "证书专业",
                "data": "certificateMajor",
                "orderable": false
            },
            {
                "title": "证书等级",
                "data": "certificateLevel",
                "orderable": false
            },
            {
                "title": "地区",
                "data": "certificateArea",
                "orderable": false
            },
            {
                "title": "适用范围",
                "data": "applicationScope",
                "orderable": false
            },
            {
                "title": "应用状态",
                "data": "status",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    if (0 == data) {
                        return '正常';
                    }
                    if (1 == data) {
                        return '停用';
                    }
                }
            },
            {
                "title": "收证指导价（元）",
                "data": "certificateGuidingPrice",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    return '<div class="operability-td line-edit">' +
                        '<input type="text"  readonly value="' + data + '" onkeyup="restrictInputLength(this,8)"/>' +
                        '</div>';
                }
            },
            {
                "title": "使用指导价（元）",
                "data": "hangUpGuidingPrice",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    return '<div class="operability-td line-edit">' +
                        '<input type="text"  readonly value="' + data + '" onkeyup="restrictInputLength(this,8)"/>' +
                        '</div>';
                }
            },
            {
                "title": "最新操作时间",
                "data": "updateTime",
                "orderable": false
            },
            {
                "title": "最新操作人",
                "data": "updaterName",
                "orderable": false
            },
            {
                "title": "操作",
                "data": "status",
                "orderable": false,
                "render": function (data, type, full, meta) {
                    var htl = '';
                    if (0 == data) {
                        htl = '<a href="javascript:void(0)" class="iboss-link" onclick="updateStatus($(this),' + meta.row + ',1)">停用</a>'
                    }
                    if (1 == data) {
                        htl = '<a href="javascript:void(0)" class="iboss-link" onclick="updateStatus($(this),' + meta.row + ',0)">启用</a>'
                    }
                    return htl + '<a href="javascript:void(0)" class="iboss-link"  onclick="editPrice($(this),' + meta.row + ')">编辑</a>'
                }
            }
        ]
    });
});

/**
 * 编辑指导价
 * @param obj
 * @param i
 */
function editPrice(obj, i) {
    console.log(obj.parents('.dataTables_wrapper').length);
    var saveHtm = '<a href="javascript:void(0)" class="iboss-link" onclick="savePrice($(this),' + i + ')">保存</a>';
    obj.parents('.dataTables_wrapper').find('#myTable tbody>tr').eq(i).find('.operability-td input').addClass('input-style').removeAttr('readonly');
    obj.parent().append(saveHtm);
    obj.remove();
}

/**
 * 保存指导价
 * @param obj
 * @param i
 */
function savePrice(obj, i) {
    var editHtm = '<a href="javascript:void(0)" class="iboss-link" onclick="editPrice($(this),' + i + ')">编辑</a>';
    obj.parents('.dataTables_wrapper').find('#myTable tbody>tr').eq(i).find('.operability-td input').removeClass('input-style').attr('readonly', 'readonly');
    var saveDate = {};
    var rowIndex = obj.parents('.dataTables_wrapper').find('#myTable tbody>tr').eq(i);
    rowIndex.find('td').each(function () {
        var idx = priceTableObj.cell(this).index().column;
        var name = priceTableObj.column(idx).dataSrc();
        var isEdit = $(this).find('.operability-td').length;
        if (isEdit != 0) {
            var value = $(this).find('.operability-td input').val();
            saveDate[name] = value;
        }
    });
    //非空校验
    for (let index in saveDate) {
        if (!saveDate[index]) {
            DGG.Warning('输入框内容不能为空');
            editPrice(obj, i);
            return false;
        }
    }
    obj.parent().append(editHtm);
    obj.remove();
    saveDate["id"] = priceTableObj.rows(rowIndex).data()[0].id;
    DGG.loading();
    $.ajax({
        type: "post",
        url: sysInfo.basePath + "/zs/guide_price_config/update_guide_price.do",
        data: saveDate,
        dataType: "json",
        success: function (result) {
            DGG.loading('close');
            if (result.code == 0) {
                DGG.Succeed('保存成功!')
            } else {
                DGG.Errors(result.msg);
            }
        }
    });
}

/**
 * 新增指导价
 */
function addPrice() {
    var isAll = "";
    var checkResult = checkHasSybAuth($('#signOrgName option'));
    if (checkResult) {
        syb("#signOrgName");
    } else {
        isAll = "0";
    }
    loadCertificateType('190px','#addType', $("#GENERAL_CREDENTIAL").val(), 0);
    //异步加载地区
    Plug.plug_ins(
        "get",
        cmsBaseUrl + "/api/cms/tree_book/v1/get_tree_book_list.do?code=2147483647&type=2&level=1",
        "#addArea",
        '请选择地区',
        function () {
        },
        true, '2147483647'
    );
    $("#certificateSpecialty").select2({
        placeholder: "请选择",
        allowClear: true,
        width: "190px",
        language: "zh-CN"
    });

    var index = dgg.Open({
        title: '新增指导价',
        content: $('#addPrice'),
        area: '550px',
        yes: function () {
            var signOrgId = $('#signOrgName').val();
            var signOrgName = $("#signOrgName option:selected").text();
            var addType = $("#addType").val();
            var addMajo = $("#addMajo").val();
            var addLevel = $("#addLevel").val();
            var addArea = $("[name='addAreaCodes']").val();
            var areaName = $("[name='areaNames']").val();
            var addScope = $('#addScope').val();
            var addGuidingPrice = $('#addGuidingPrice').val();
            var status = addCheck(signOrgId, addType, addMajo, addLevel, addArea, addScope, addGuidingPrice, isAll);
            if (!status) {
                return false;
            }
            DGG.Confire('确认执行此操作？', '操作提示', function () {
                DGG.loading();
                $.ajax({
                    type: "post",
                    url: sysInfo.basePath + "/zs/guide_price_config/add_guide_price.do",
                    data: {
                        "isAll": isAll,
                        "signOrgId": signOrgId,
                        "signOrgName": signOrgName,
                        "certificateTypeId": addType,
                        "certificateMajorId": addMajo,
                        "certificateLevel": addLevel,
                        "certificateArea": addArea,
                        "applicationScope": addScope,
                        "certificateGuidingPrice": addGuidingPrice,
                        "provinceArea": areaName
                    },
                    dataType: "json",
                    success: function (result) {
                        DGG.loading('close');
                        layer.close(index);
                        if (result.code == 0) {
                            DGG.Succeed('添加配置成功！');
                            $('#myTable').dataTableExtend("reload");
                            clear("#addPrice");
                        } else {
                            DGG.Errors(result.msg);
                        }
                    }
                });
            });
        }
    })

}

/**
 * 复制指导价
 */
function copyPrice() {
    syb("#copySignOrgName");
    var index = dgg.Open({
        title: '复制指导价',
        content: $('#copyPrice'),
        area: '480px',
        yes: function () {
            var copySignOrgName = $('#copySignOrgName').val();
            var copyDate = $("#copyDate").val();
            var checkResult = checkHasSybAuth($('#copySignOrgName option'));
            var isAll = "";
            if (!checkResult) {
                copySignOrgName = 0;
                isAll = "0";
            } else if (!copySignOrgName) {
                DGG.Warning('请选择事业部');
                return false;
            }
            if (!copyDate) {
                DGG.Warning("请选中复制时间");
                return false;
            }
            DGG.loading();
            $.post(sysInfo.basePath + "/zs/guide_price_config/check_guide_pricec.do?signOrgId=" + copySignOrgName, {}, function (result) {
                DGG.loading('close');
                if (result.code != 0) {
                    DGG.Confire(result.msg, '操作提示', function () {
                        saveCopy(index, copySignOrgName, copyDate, isAll);
                        clear("#copyPrice");
                    });
                } else {
                    saveCopy(index, copySignOrgName, copyDate, isAll);
                }
            });
        }
    })
}

/**
 * 请求复制
 * @param signOrgId
 * @param month
 */
function saveCopy(index, signOrgId, month, isAll) {
    DGG.loading();
    $.ajax({
        type: "post",
        url: sysInfo.basePath + "/zs/guide_price_config/copy_guide_price.do",
        data: {
            "signOrgId": signOrgId,
            "month": month,
            "isAll": isAll
        },
        dataType: "json",
        success: function (result) {
            DGG.loading('close');
            if (result.code == 0) {
                layer.close(index);
                DGG.Succeed('添加配置成功！', '操作成功');
                $('#myTable').dataTableExtend("reload");
            } else {
                DGG.Errors(result.msg);
            }
        }
    });
}


/**
 * 修改状态
 */
function updateStatus(obj, i, type) {
    DGG.Confire(type == 0 ? '确认要启用?' : '确认要停用?', '操作提示', function () {
        var rowIndex = obj.parents('.dataTables_wrapper').find('#myTable tbody>tr').eq(i);
        var guidePriceId = priceTableObj.rows(rowIndex).data()[0].id;
        $.post(sysInfo.basePath + "/zs/guide_price_config/update_status.do?guidePriceId=" + guidePriceId + "&type=" + type, {}, function (result) {
            if (result.code == 0) {
                DGG.Succeed(type == 0 ? '启用成功' : '停用成功')
                $('#myTable').dataTableExtend("reload");
            } else {
                DGG.Errors("系统错误，请联系管理员");
            }
        });
    });
}

/**
 * 导出数据
 */
function exportGuidePrice() {
    var startDate = $('#startDate').val();
    var endDate = $('#endDate').val();
    var signOrgId = $('#selectSignOrgName').val() == 0 ? "" : $('#selectSignOrgName').val();
    var certificateType = $("#certificateType").val();
    var certificateSpecialty = $("#certificateSpecialty").val();
    var certificateArea = $("[name='certificateAreaCodes']").val();
    var applicationScope = $('#applicationScopes').val();
    var certificateLevel = "";
    if ($("#certificateLevel").val()) {
        certificateLevel = $("#certificateLevel option:selected").text()
    }
    if (!startDate && !endDate && !signOrgId && !certificateType && !certificateSpecialty && !certificateLevel && !certificateArea && !applicationScope) {
        DGG.Alert_warning('请选择导出条件！');
        return false;
    } else {
        var params = {};
        params["startDate"] = startDate;
        params["endDate"] = endDate;
        params["signOrgId"] = signOrgId;
        params["certificateType"] = certificateType;
        params["certificateSpecialty"] = certificateSpecialty;
        params["certificateLevel"] = certificateLevel;
        params["certificateArea"] = certificateArea;
        params["applicationScope"] = applicationScope;
        export_table("/zs/guide_price_config/export_guide_price.do", params)
    }
}

/**
 *添加非空校验
 */
function addCheck(signOrgId, addType, addMajo, addLevel, addArea, addScope, addGuidingPrice, isAll) {
    if (!signOrgId && isAll != "0") {
        DGG.Warning('请选择事业部');
        return false;
    }
    if (!addType) {
        DGG.Warning('请选择证书类型');
        return false;
    }
    if (!addMajo) {
        DGG.Warning('请选择证书专业');
        return false;
    }
    if (!addLevel) {
        DGG.Warning('请选择证书等级');
        return false;
    }
    if (!addArea) {
        DGG.Warning('请选择地区');
        return false;
    }
    if (!addScope) {
        DGG.Warning('请选择适用范围');
        return false;
    }
    if (!addGuidingPrice) {
        DGG.Warning('请填写指导价格');
        return false;
    }
    return true;
}

/**
 * 清空div的值
 */
function clear(obj) {
    var $s = $(obj);
    $s.find('input').val('');
    $s.find('select').val('');
    $s.find('select').val(null).trigger("change");
    $s.find('input').attr("data-id", '');
}